<template>
  <div class="page-wrap">
    <el-card shadow="never">
      <div class="toolbar">
        <el-date-picker v-model="range" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        <el-button @click="refresh">刷新</el-button>
      </div>

      <el-table :data="rows" border stripe>
        <el-table-column prop="season" label="季节" width="120" />
        <el-table-column prop="qty" label="销量" width="120" />
        <el-table-column prop="amount" label="金额(估)" width="140" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useStockStore } from '@/stores/stock.js'
import { useProductStore } from '@/stores/product.js'

const stock = useStockStore()
const product = useProductStore()
const range = ref([])
const rows = ref([])

onMounted(() => { if(!stock.stockList.length) stock.initializeStock(); if(!product.productList.length) product.initializeProducts(); refresh() })

function inRange(dateIso){
  if (!range.value || range.value.length !== 2) return true
  const [start, end] = range.value
  const d = new Date(dateIso).toISOString().slice(0,10)
  return (!start || d >= start) && (!end || d <= end)
}

function seasonOf(p){
  const s = (p?.season || '').toLowerCase()
  if (['spring','春','春季'].includes(s)) return '春'
  if (['summer','夏','夏季'].includes(s)) return '夏'
  if (['autumn','fall','秋','秋季'].includes(s)) return '秋'
  if (['winter','冬','冬季'].includes(s)) return '冬'
  return '未设'
}

function refresh(){
  const outbound = stock.getStockHistory(null, 'outbound').filter(r => inRange(r.date))
  const pidToProduct = Object.fromEntries(product.productList.map(p => [p.id, p]))
  const map = { '春':{qty:0,amount:0}, '夏':{qty:0,amount:0}, '秋':{qty:0,amount:0}, '冬':{qty:0,amount:0}, '未设':{qty:0,amount:0} }
  outbound.forEach(r => {
    const p = pidToProduct[r.productId]
    const key = seasonOf(p)
    const price = Number(p?.salePrice || 0)
    map[key].qty += Number(r.quantity || 0)
    map[key].amount += Number(r.quantity || 0) * price
  })
  rows.value = Object.entries(map).map(([season, v]) => ({ season, qty: v.qty, amount: Number(v.amount.toFixed(2)) }))
}
</script>

<style scoped>
.page-wrap { padding: 16px; }
.toolbar { display: flex; gap: 12px; align-items: center; }
</style>


